package com.vaadin.thomas.contenttool;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.vaadin.thomas.contenttool.data.Model;
import com.vaadin.thomas.contenttool.data.ModelFactory;
import com.vaadin.thomas.contenttool.ui.AdminUIBootstrapper;

/**
 * Helper class for initializing {@link Model}s. Extend this class and add it as
 * a context listener in your web.xml:
 * <p>
 * <code>&lt;listener&gt;<br/>
		&lt;listener-class>com.vaadin.thomas.contenttool.demo.DemoBootstrapper&lt;/listener-class&gt;<br/>
	&lt;/listener&gt;</code>
 * <p>
 * The listener methods will be triggered on servlet startup and shutdown.
 * 
 * @author Thomas Mattsson / Vaadin OY
 * 
 */
public abstract class AbstractInitializer implements ServletContextListener {

	protected Config conf;
	protected Model model;

	protected AbstractInitializer(Config conf) {
		this.conf = conf;
	}

	@Override
	public final void contextDestroyed(ServletContextEvent arg0) {

		preDestroy();
		ModelFactory.destroy(conf.getModelId());
		postDestroy();
	}

	@Override
	public final void contextInitialized(ServletContextEvent arg0) {

		preInit();

		model = ModelFactory.initialize(conf);

		if (conf.bootstrapUIValues()) {
			new AdminUIBootstrapper(model, true);
		}

		postInit();
	}

	protected abstract void preInit();

	protected abstract void postInit();

	protected abstract void preDestroy();

	protected abstract void postDestroy();

}
